package com.hznu.coursemanagerbackend.modules.sys.controller;


import com.google.api.client.util.Value;
import com.hznu.coursemanagerbackend.common.ueditor.ActionEnter;
import com.hznu.coursemanagerbackend.common.utils.FileUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * @Author: TateBrown
 * @date: 2018/12/31 12:42
 * @param:
 * @return:
 */
@RestController
@CrossOrigin
@RequestMapping("/ueditor")
public class UeditorController extends AbstractController {

    @Value("${pathconfig.picpath}")
    private static String picPath = "/www/Image/";

    @RequestMapping(value = "/exec")
    @ResponseBody
    public String exec(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        String rootPath = request.getRealPath("/");
        return new ActionEnter(request, rootPath).exec();
    }

    /**
     * @Description:提供富文本直链下载路径
     * @param:
     * @return:
     * @author: TateBrown
     * @Date: 2019/1/16
     */
    @ApiOperation("提供富文本附件文件下载直链")
    @GetMapping("/file/{filename:.+}")
    public ResponseEntity<Resource> file(HttpServletRequest request, @PathVariable String filename) {
        try {
            Resource resource = null;

            resource = new FileSystemResource(picPath + filename);
            String filenames = new String(filename.getBytes(StandardCharsets.UTF_8),   StandardCharsets.ISO_8859_1);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", filenames);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(resource.getInputStream().available())
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(resource);

        } catch (Exception e) {
            logger.error(e.toString());
            return null;
        }
    }
}
